package com.fafu.service.Impl;

import com.fafu.dao.mapper.AreaMapper;
import com.fafu.dao.mapper.StudentMapper;
import com.fafu.model.Area;
import com.fafu.model.Student;
import com.fafu.pojo.StudentInsertPojo;
import com.fafu.service.ToolService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import util.MD5Utils;
import util.MyMap;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ToolServiceImpl implements ToolService {
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private StudentMapper studentMapper;
    private Map<String,Integer> areaMap;
    @Transactional
    @Override
    public Map<String, Object> studentInsert(Map<String, Object> paramMap) throws IOException {
        StudentInsertPojo shine = (StudentInsertPojo) paramMap.get("shine");
        String fileUrl = (String) paramMap.get("fileUrl");
        InputStream is = new FileInputStream(fileUrl);
        boolean isExcel2003 = true;
        if (fileUrl.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        Workbook wb = null;
        if (isExcel2003)
            wb = new HSSFWorkbook(is);
        else
            wb = new XSSFWorkbook(is);
        //开始持久化操作
        int successCount = 0;//成功插入条数
        int failCount = 0; //失败插入条数
        List<String> failIden = new ArrayList();
        Sheet sheet = wb.getSheetAt(0);
        int rowCount = sheet.getLastRowNum();
        String pp = MD5Utils.MD5("666666");
        String salt = MD5Utils.createSalt();
        String password = MD5Utils.passwordAddSalt(pp, salt);
        for (int i = 1; i <= rowCount; i++) { //0为title
            Row row = sheet.getRow(i);
            Student student = new Student();
            student.setIsUsed(1);
            student.setPassword(password);
            student.setSalt(salt);

            row.getCell(shine.getArea()).setCellType(Cell.CELL_TYPE_STRING);
            Integer areaId = getAreaId(row.getCell(shine.getArea()).getStringCellValue());
            student.setArea(areaId);

            row.getCell(shine.getGender()).setCellType(Cell.CELL_TYPE_STRING);
            student.setGender(getGenderId(row.getCell(shine.getGender()).getStringCellValue()));

            row.getCell(shine.getStudentName()).setCellType(Cell.CELL_TYPE_STRING);
            student.setStudengName(row.getCell(shine.getStudentName()).getStringCellValue());

            row.getCell(shine.getStudentAddr()).setCellType(Cell.CELL_TYPE_STRING);
            student.setStudentAddr(row.getCell(shine.getStudentAddr()).getStringCellValue());

            row.getCell(shine.getStudentIden()).setCellType(Cell.CELL_TYPE_STRING);
            student.setStudentIden(row.getCell(shine.getStudentIden()).getStringCellValue());
            Example example = new Example(Student.class);
            example.and().andEqualTo("studentIden",student.getStudentIden());
            List<Student> checkList = studentMapper.selectByExample(example);
            if(checkList != null && checkList.size() >0) {//已存在该学号的学生
                failCount++;
                failIden.add(student.getStudentIden());
                continue;
            }
            studentMapper.insertSelective(student);
            successCount++;
        }
        return new MyMap()
                .put("successCount",successCount)
                .put("failCount",failCount)
                .put("failIden",failIden).toMap();
    }
    private Integer getAreaId(String key){
        if(areaMap == null)
            getAreaMap();
        Integer id = areaMap.get(key);
        if(id == null){
            addArea(key);//插入
            getAreaMap();//重新取值
            return getAreaId(key);
        }
        return id;
    }
    private void getAreaMap() {
        List<Area> areas = areaMapper.selectAll();
        areaMap=new HashMap<>();
        for(Area data:areas)
            areaMap.put(data.getAreaName(),data.getId());

    }
    private void addArea(String name){
        Area area = new Area();
        area.setAreaName(name);
        areaMapper.insert(area);
        getAreaMap();
    }

    private Integer getGenderId(String key) {
        if (key.equals("男"))
            return 1;
        else if (key.equals("女"))
            return 2;
        else
            return -1;
    }
}
